package com.suyeer.common;

import com.alibaba.fastjson.annotation.JSONField;
import com.suyeer.basic.bean.BaseHttpResContent;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by jun on 2017/7/21.
 */
public class HttpResContent<T> extends BaseHttpResContent<T> {
    private static final long serialVersionUID = 5640118292870299785L;
    private static final String KEY_TRANSACTION_MANAGER = "transactionManager";
    private transient Boolean ifAtomicity;
    private transient DataSourceTransactionManager transactionManager;
    private transient TransactionStatus transactionStatus;
    private transient HttpStatusEnum httpStatus;

    public HttpResContent(HttpServletRequest request, HttpServletResponse response) {
        this(request, response, false);
    }

    public HttpResContent(HttpServletRequest request, HttpServletResponse response, boolean ifAtomicity) {
        super(request, response);
        this.ifAtomicity = ifAtomicity;
        this.httpStatus = HttpStatusEnum.REPEAT_LOGIN;
        if (ifAtomicity) {
            transactionManager = SpringFactory.getBean(KEY_TRANSACTION_MANAGER);
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            this.transactionStatus = transactionManager.getTransaction(def);
        }
    }

    public void commit() {
        if (this.ifAtomicity) {
            this.transactionManager.commit(this.transactionStatus);
        }
    }

    public void rollback() {
        if (this.ifAtomicity) {
            this.transactionManager.rollback(this.transactionStatus);
        }
    }

    @Override
    public Boolean isPermission() {
        return true;
    }

    @JSONField(serialize = false)
    public Boolean isNotPermission() {
        return false;
    }

    @Override
    public Object getUserInfo() {
        return null;
    }

    @Override
    public Object getWxUserInfo() {
        return null;
    }

    @Override
    public Boolean isLogin() {
        return true;
    }

    public HttpStatusEnum getHttpStatus() {
        return httpStatus;
    }

    @Override
    public Boolean isWxLogin() {
        return super.isWxLogin;
    }

    @JSONField(serialize = false)
    public Boolean isNotLogin() {
        return !isLogin();
    }

}
